<template>
  <div style="height: 100vh; overflow: hidden">
    <div
        style="height: 50px; line-height: 50px; border-bottom: 2px solid var(--colorRed); padding-left: 50px; color: var(--colorRed)">
      <b style="font-size: 24px;">趣猫</b>
      <i style="margin-left: 20px">-- 只为小白的你</i>
    </div>

    <div
        style="width: 50%; margin: 150px auto; border-radius: 10px; box-shadow: 0 0 10px -2px cornflowerblue; display: flex;">
      <div style="flex: 1; padding: 100px 50px">
        <img src="../assets/imgs/打折促销.png" alt="" style="width: 100%;">
      </div>

      <div style="flex: 1; padding: 50px">
        <div class="form-toggle">
          <b :class="{'active': activeToggle === 'account'}" @click="toggle('account')">账号登录</b>
          <b :class="{'active': activeToggle === 'phone'}" style="margin-left: 10px"
             @click="toggle('phone')">手机号登录</b>
        </div>

        <el-form ref="form" :rules="rules" :model="loginForm" v-show="activeToggle === 'account'">
          <el-form-item prop="account">
            <el-input size="medium" v-model="loginForm.account" prefix-icon="el-icon-user"
                      placeholder="请输入账号/邮箱/手机号"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input size="medium" show-password v-model="loginForm.password" prefix-icon="el-icon-lock"
                      placeholder="请输入密码"></el-input>
          </el-form-item>
          <div style="margin: 10px 0; text-align: right">
            忘记密码
          </div>
          <div>
            <el-button type="primary" size="medium" style="width: 100%" @click="login('/session/login')">登录</el-button>
          </div>
          <div style="margin: 10px 0; text-align: right;">
            <a href="/#/register" style="color: var(--colorRed)">立即注册</a>
          </div>
        </el-form>

        <!--  手机号 登录 -->
        <el-form ref="formPhone" :rules="rulesPhone" :model="loginForm" v-show="activeToggle === 'phone'">
          <el-form-item prop="account">
            <el-input size="medium" v-model="loginForm.account" prefix-icon="el-icon-user" placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item prop="smsCode">
            <div style="display: flex;">
              <el-input size="medium" style="flex: 2" v-model="loginForm.smsCode"
                        prefix-icon="el-icon-circle-check"  placeholder="请输入验证码"></el-input>
              <el-button :disabled="second > 0" size="medium" style="flex: 1; margin-left: 5px" @click="sendSMS">点击发送
                <span v-if="second > 0">({{ second }})</span></el-button>
            </div>
          </el-form-item>

          <div>
            <el-button type="primary" size="medium" style="width: 100%" @click="login('/session/loginsms')">登录</el-button>
          </div>
          <div style="margin: 10px 0; text-align: right;">
            <a href="/#/register" style="color: var(--colorRed)">立即注册</a>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "Login",
  data() {
    const checkPhone = (rule, value, callback) => {
      if(!this.validatePhone.test(value)) {
        return callback(new Error('手机号格式不合法'));
      }
      callback()
    }

    const checkSMS = (rule, value, callback) => {
      if(!/\d{6}/.test(value)) {
        return callback(new Error('验证码必须是数字且长度必须是6位'));
      }
      callback()
    }
    return {
      loginForm: {},
      activeToggle: 'phone',  // 小坑：变量名不能跟方法名一样  account | phone
      second: 0,
      rules: {
        account: [
          {required: true, message: '请输入用户名/邮箱/手机号', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
        ]
      },
      rulesPhone: {
        account: [
          { validator: checkPhone, trigger: 'blur' }
        ],
        smsCode: [
          { validator: checkSMS, trigger: 'blur' }
          // { required: true, message: '年龄不能为空'},
          // { type: 'number', message: '验证码必须为数字值'},
          // { min: 6, max: 6, message: '长度必须6位'},
        ]
      },
      interval: null,
      validatePhone: /^1[3,4,5,6,7,8,9][0-9]{9}$/
    }
  },
  methods: {
    toggle(active) {
      this.activeToggle = active
      // 在切换表单的时候 清空表单
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
      if (this.$refs.formPhone) {
        this.$refs.formPhone.resetFields()
      }
      this.loginForm = {}
    },
    sendSMS() {
      // 校验是否合法
      if(!this.validatePhone.test(this.loginForm.account)) {
        this.$message.warning("手机号格式不合法")
        return
      }

      // 防止点击太快，没来得及清理
      if (this.interval) {
        clearInterval(this.interval)
      }
      this.second = 30
      this.interval = setInterval(() => {  // 注意：这个方法会一直干到死
        if (this.second > 0) {
          this.second--
        } else {
          clearInterval(this.interval)   // 干到 second = 0 为止
          this.interval = null
        }
      }, 1000)

      // 发送验证码
      request.get('/session/sms', {
        params: {
          account: this.loginForm.account
        }
      }).then(res => {
        if (res.code === '200') {
          this.$message.success('发送成功')
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    login(url) {
      let form = 'form'
      if (!url) {
        return
      } else if (url.includes('/loginsms')) {
        form = 'formPhone'
      }
      // 请求后台接口
      this.$refs[form].validate((valid) => {
        if (valid) {   // 验证通过
          request.post(url, this.loginForm).then(res => {
            if (res.code === '200') {
              // 存数据
              this.$store.commit('setLoginData', res.data)
              this.$router.push('/') // 跳转到主页
              this.$message.success('登录成功')
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.form-toggle {
  margin: 20px 0;
  text-align: center
}

.form-toggle b {
  font-size: 20px;
  cursor: pointer;
}

.active {
  color: var(--colorRed);
}
</style>